/**
   pattern  dp g f e d c b a
      0      0 0 1 1 1 1 1 1    0x3F
      1      0 0 0 0 0 1 1 0    0x06
      2      0 1 0 1 1 0 1 1    0x5B
      3      0 1 0 0 1 1 1 1    0x4F
      4      0 1 1 0 0 1 1 0    0x66
      5      0 1 1 0 1 1 0 1    0x6D
      6      0 1 1 1 1 1 0 1    0x7D
      7      0 0 0 0 0 1 1 1    0x07
      8      0 1 1 1 1 1 1 1    0x7F
      9      0 1 1 0 1 1 1 1    0x6F
      
*/

uint32_t led_time;
int seg_pin[8]={A0, A1, A2, A3, A4, A5, 6, 7};
int seg_tab[10] = {
  0x3F, 0x06, 0x5B, 0x4F, 0x66,
  0x6D, 0x7D, 0x07, 0x7F, 0x6F
};
void seg_write(uint8_t value)
{
  int i;
  if(value>9){
    return; 
  }
  value = seg_tab[value];
  for(i=0; i<8; i++){
    if(value&(1<<i)){
      digitalWrite(seg_pin[i], HIGH);
    }else{
      digitalWrite(seg_pin[i], LOW);
    }
  }
}

void setup(void)
{
  Serial.begin(115200);
  Serial.println("Proteus&Arduino");
  Serial.println("Chapter 01");
  
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  led_time = millis();
  
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
  pinMode(A3, OUTPUT);
  pinMode(A4, OUTPUT);
  pinMode(A5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(3, OUTPUT);
  
  analogWrite(9, 20);
  analogWrite(10, 40);
  analogWrite(11, 80);
  analogWrite(3, 160);
}

void loop(void)
{
  uint8_t ascii;
  if(Serial.available()){
    ascii = Serial.read();
    if(ascii >= '0' && ascii <= '9'){
      Serial.print("Received: ");
      Serial.write(ascii);
      Serial.println();
      seg_write(ascii-'0');
    }
  }
  if(millis()-led_time > 250){
    led_time = millis();
    if(digitalRead(13) == HIGH){
      digitalWrite(13, LOW);
    }else{
      digitalWrite(13, HIGH);
    }
  }
}
